<script lang="ts" setup>
import type { InfoStoreApi } from '#/api/spa/store';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { message } from 'ant-design-vue';

import { $t } from '#/locales';
import { useVbenForm } from '#/adapter/form';
import {
  createInfoStore,
  getInfoStoreWithGroup,
  updateInfoStore,
} from '#/api/spa/store';
import { getSiteList } from '#/api/spa/site';

import { useFormSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<InfoStoreApi.InfoStore>();
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['门店'])
    : $t('ui.actionTitle.create', ['门店']);
});


const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 80,
  },
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    // 提交表单
    const data = (await formApi.getValues()) as InfoStoreApi.InfoStore;

    // 处理站点信息的数据转换
    if (data.siteIds && Array.isArray(data.siteIds)) {
      // 获取站点详细信息并转换为JSON格式
      try {
        const siteListResponse = await getSiteList();
        const siteList = siteListResponse.data || [];
        
        const selectedSites = data.siteIds.map((id: number) => {
          const site = siteList.find((s: any) => s.site_id === id);
          return site ? {
            siteId: site.site_id,
            siteName: site.site_name,
            siteDomain: site.site_domain,
            groupId: site.group_id,
            groupName: site.group_name,
            status: site.status,
            statusName: site.status_name
          } : { siteId: id };
        });
        
        data.siteInfo = JSON.stringify(selectedSites);
      } catch (error) {
        console.error('获取站点信息失败:', error);
        // 降级处理：只保存站点ID
        data.siteInfo = JSON.stringify(
          data.siteIds.map((id: number) => ({ siteId: id })),
        );
      }
      // 删除siteIds字段，因为后端只需要siteInfo
      delete data.siteIds;
    }

    try {
      await (formData.value?.id
        ? updateInfoStore(data)
        : createInfoStore(data));
      // 关闭并提示
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }
    // 加载数据
    let data = modalApi.getData<InfoStoreApi.InfoStore>();
    if (!data) {
      return;
    }
    if (data.id) {
      modalApi.lock();
      try {
        data = await getInfoStoreWithGroup(data.id);
      } finally {
        modalApi.unlock();
      }
    }
    // 设置到 values
    formData.value = data;
    
    // 处理站点信息的数据转换
    if (data.siteInfo) {
      try {
        const siteInfo = JSON.parse(data.siteInfo);
        if (Array.isArray(siteInfo)) {
          // 将JSON格式的站点信息转换为站点ID数组
          data.siteIds = siteInfo.map((site: any) => site.siteId);
        }
      } catch (error) {
        console.error('解析站点信息失败:', error);
        // 如果解析失败，尝试从旧的简单格式中提取
        if (typeof data.siteInfo === 'string' && data.siteInfo.includes('siteId')) {
          try {
            const parsed = JSON.parse(data.siteInfo);
            if (Array.isArray(parsed)) {
              data.siteIds = parsed.map((item: any) => item.siteId || item);
            }
          } catch (e) {
            console.error('解析旧格式站点信息失败:', e);
          }
        }
      }
    }
    
    await formApi.setValues(formData.value);
  },
});
</script>

<template>
  <Modal :title="getTitle">
    <Form class="mx-4" />
      </Modal>
</template>
